const api = require('../../utils/api');
const app = getApp();

Page({
  data: {
    courseId: '',
    name: '',
    teacher: '',
    location: '',
    weekday: 1,
    startTime: '08:00',
    endTime: '09:40',
    weekType: 0,
    selectedWeeks: [],
    weekdays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    submitting: false,
    loading: true
  },

  onLoad: function(options) {
    this.setData({ courseId: options.id });
    this.loadCourseData();
  },

  loadCourseData: async function() {
    try {
      const courses = await api.course.list(app.globalData.userId);
      const course = courses.find(c => c.id === this.data.courseId);
      
      if (course) {
        this.setData({
          name: course.name,
          teacher: course.teacher || '',
          location: course.location || '',
          weekday: course.weekday,
          startTime: course.start_time.slice(0, 5),
          endTime: course.end_time.slice(0, 5),
          weekType: course.week_type,
          selectedWeeks: course.weeks,
          loading: false
        });
      }
    } catch (error) {
      console.error('获取课程数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 更新课程
  updateCourse: async function() {
    if (!this.validateForm()) {
      return;
    }

    try {
      this.setData({ submitting: true });
      
      const courseData = {
        name: this.data.name,
        teacher: this.data.teacher,
        location: this.data.location,
        weekday: this.data.weekday,
        startTime: this.data.startTime,
        endTime: this.data.endTime,
        weekType: this.data.weekType,
        weeks: this.data.selectedWeeks
      };

      await api.course.update(this.data.courseId, courseData);
      
      wx.showToast({
        title: '更新成功',
        icon: 'success'
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    } catch (error) {
      console.error('更新课程失败:', error);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 删除课程
  deleteCourse: async function() {
    try {
      await wx.showModal({
        title: '确认删除',
        content: '确定要删除这门课程吗？'
      });

      await api.course.delete(this.data.courseId);
      
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    } catch (error) {
      console.error('删除课程失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  }
});